package com.chain.voter;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chain.voter.adapter.VoteAdapter;
import com.chain.voter.modle.BaseResponse;
import com.chain.voter.modle.VoteCard;
import com.chain.voter.record.FavouriteShare;
import com.chain.voter.record.ShareListModel;
import com.chain.voter.record.ShareModel;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.naschain.naspay.NasPayManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chain.voter.Contracts.CONTRACT_ADDRESS;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "VoterMainActivity";

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    VoteAdapter voteAdapter;
    List<VoteCard> voteCardList = new ArrayList<>();

    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;

    @BindView(R.id.publish)
    View publish;

    @BindView(R.id.refreshbtn)
    View refreshbtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        NasPayManager.Default_Contract_Address = CONTRACT_ADDRESS;

        refreshLayout.setRefreshing(true);
        refreshData();
        initViews();



        /*{
            "Function": "save",
                "Args": "[\"复联谁最厉害\",\"2018-05-12\",\"2018-05-31\",\"钢铁侠;美队;雷神;绿巨人;黑寡妇;\"]"
        }*/
        /*NasPayManager.createCallBuilder(this)
                .setFunctionName("save")
                .setArgs(new String[]{"世界上最高的动物",getCurrentDate(),getCurrentDate(),"老鼠;大象;长颈鹿;"})
                .setSerialNumber(Util.getRandomCode(32))
                .build();
*/
         /*NasPayManager.createCallBuilder(this)
                .setFunctionName("update")
                .setArgs(new String[]{"0","0_1"})
                .setSerialNumber(Util.getRandomCode(32))
                .build();*/


    }

    @Override
    protected void onResume() {
        super.onResume();
        checkRefreshBtn();
    }

    private void checkRefreshBtn(){
        ShareListModel shareListModel = FavouriteShare.getPendingPayRecord(this);
        if(shareListModel.getShareModelList().size()!=0){
            refreshbtn.setVisibility(View.VISIBLE);
        }else{
            refreshbtn.setVisibility(View.GONE);
        }
    }

    private void initViews() {
        voteAdapter = new VoteAdapter(voteCardList);
        recyclerView.setAdapter(voteAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
    }

    private void refreshData() {
        NasPayManager.createSimulateCallBuilder().setFunctionName("getAll").setOnNasSimulateCallListener(new NasPayManager.OnNasSimulateCallListener() {

            @Override
            public void onSuccess(final String response) {
                Log.d(TAG, "onSuccess() called with: response = [" + response + "]");
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        refreshLayout.setRefreshing(false);
                        Gson gson = new Gson();
                        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
                        if (baseResponse.getResult() != null) {
                            String result = baseResponse.getResult().getResult();
                            if (result != null) {
                                Log.d(TAG, "onSuccess() called with: response = [" + result + "]");
                                List<VoteCard> voteCards = gson.fromJson(result, new TypeToken<List<VoteCard>>() {
                                }.getType());
                                voteCardList.clear();
                                for (int i = voteCards.size() - 1; i >= 0; i--) {
                                    voteCardList.add(voteCards.get(i));
                                }
                                voteAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }

            @Override
            public void onError(final String error) {
                Log.d(TAG, "onError() called with: error = [" + error + "]");
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                        Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
                    }
                });

            }
        }).build();


        ShareListModel shareListModel = FavouriteShare.getPendingPayRecord(this);
        String content = "您还有以下操作正在进行中：";
        boolean flag = false;
        for (ShareModel shareModel : shareListModel.getShareModelList()) {
            flag = true;
            content += "\n"+shareModel.getExtra();
            NasPayManager.queryNasPay(shareModel.getUnicode(), new NasPayManager.OnNasPayUtilListener() {
                @Override
                public void success(String unicode) {
                    final String extra = FavouriteShare.removePendingPayRecord(MainActivity.this, unicode);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "操作成功，关于"+extra, Toast.LENGTH_SHORT)
                                    .show();

                            checkRefreshBtn();
                        }
                    });
                }

                @Override
                public void fail(String unicode, final String msg) {
                    final String extra = FavouriteShare.removePendingPayRecord(MainActivity.this, unicode);
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "支付失败，关于"+extra, Toast.LENGTH_SHORT)
                                    .show();

                            checkRefreshBtn();
                        }
                    });
                }
            });
        }
        if(flag == true){
            refreshbtn.setVisibility(View.VISIBLE);
            Toast.makeText(MainActivity.this,content,Toast.LENGTH_SHORT).show();
        }else{
            refreshbtn.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.refreshbtn)
    public void onRefreshBtn(){
        refreshLayout.setRefreshing(true);
        refreshData();
    }

    public static String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    @OnClick(R.id.publish)
    public void onPublish() {
        startActivity(new Intent(this, PublishActivity.class));
    }
}
